package actions

import (
	"errors"
	"haili/models"
	"haili/services"

	"net/http"

	"haili/common"

	"fmt"

	"github.com/lunny/tango"
)

type UserAction struct {
	tango.Json
	tango.Ctx
}

var userService services.UserService

//新增用户
func (act UserAction) Post() interface{} {

	username := act.Ctx.Form("username") // return string
	password := act.Ctx.Form("password") // return string

	users := userService.GetUsers(map[string]interface{}{"Name": username, "PassWord": password})
	if len(users) > 0 {
		return "登录成功"
	}
	return errors.New("something error")
}

//验证用户登录
func (act UserAction) Get() interface{} {
	return ""
}
func (a UserAction) Options() interface{} {
	return http.StatusOK
}

//func RegisterUser(ctx *tango.Context) 注册用户
func RegisterUser(ctx *tango.Context) common.Data {
	var user models.User
	phone := ctx.Form("phone")
	password := ctx.Form("password")

	user.Phone = phone
	user.PassWord = password

	b, e := userService.CheckPhone(user)
	if b {
		e := userService.AddUser(user)
		if nil != e {
			return common.ReturnMesg(false, e.Error(), nil)
		}
		return common.ReturnMesg(true, "新增用户成功", nil)
	} else {
		return common.ReturnMesg(false, "新增用户失败", e.Error())
	}
}

func Login(ctx *tango.Context) common.Data {
	var user models.User
	phone := ctx.Form("phone")
	body, _ := ctx.Body()

	fmt.Println("phone", "|||||", ctx.Params(), "|||||", ctx.Forms(), string(body))
	password := ctx.Form("password")

	user.Phone = phone
	user.PassWord = password
	fmt.Println("user", user)
	s, e := userService.GetUser(user)
	if nil != e {
		return common.ReturnMesg(false, e.Error(), nil)
	}
	if s {
		return common.ReturnMesg(true, "验证用户成功", nil)
	}
	return common.ReturnMesg(false, "验证用户失败", nil)
}

//修改用户
func UpdateUser(ctx *tango.Context) common.Data {
	var user models.User
	user.Phone = ctx.Form("Phone")
	user.PassWord = ctx.Form("PassWord")
	user.NickName = ctx.Form("NickName")
	user.Name = ctx.Form("Name")
	user.IDCard = ctx.Form("IDCard")
	user.BankCard = ctx.Form("BankCard")
	user.Country = ctx.Form("Country")
	user.Address = ctx.Form("Address")
	user.Type = ctx.Form("Type")
	user.Status = ctx.Form("Status")
	user.ReMark = ctx.Form("ReMark")
	err := userService.UpdateUser(user)
	if nil != err {
		return common.ReturnMesg(false, "修改用户失败", nil)
	}
	return common.ReturnMesg(true, "修改用户成功", nil)
}

//CheckPhone fuc
func vaildPhone(ctx *tango.Context) common.Data {
	var user models.User
	phone := ctx.Form("phone")
	user.Phone = phone
	b, e := userService.CheckPhone(models.User{Phone: phone})

	if nil != e {
		return common.ReturnMesg(false, e.Error(), nil)
	}
	if b {
		return common.ReturnMesg(true, phone+"可以注册", nil)
	}
	return common.ReturnMesg(false, "验证用户失败", e.Error())
}
